package com.heima.search.service.Impl;

import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.util.AppThreadLocal;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.search.ApArticleSearchRepository;
import com.heima.search.service.IArticleLoadService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {
    @Autowired
    private ApArticleSearchRepository searchRepository;

    @Autowired
    private IArticleLoadService articleLoadService;

    /**
     * 搜索分页查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
//        校验数据
        if (StringUtils.isEmpty(dto.getSearchWords()) || StringUtils.isEmpty(dto.getSearchWords().trim())){
            return ResponseResult.okResult();
        }
//        分页查询
        QueryBuilder query = QueryBuilders.matchQuery("title",dto.getSearchWords());
        Pageable page = PageRequest.of(dto.getPage().intValue() - 1 ,dto.getSize(), Sort.Direction.DESC,"publishTime");
        Page<ApArticleSearch> search = searchRepository.search(query, page);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage() ,dto.getSize() ,search.getTotalElements(),search.getContent());
//        异步调用添加搜索记录
        User user = AppThreadLocal.get();
        Integer userId = null;
        if (user != null){
            userId = user.getUserId();
        }
        articleLoadService.saveSearchRecord(userId,dto.getEquipmentId(),dto.getSearchWords());
        return pageResponseResult;
    }
}
